﻿using FlashPay.DAO.Interface;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Response.Permission;
using FlashPay.Service.Interface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using FlashPay.Entity.Request.Permission;
using FlashPay.Entity.Enum;
using Newtonsoft.Json;
using FlashPay.Entity.Request;

namespace FlashPay.Service.Impl
{
    /// <summary>
    /// 功能权限业务代码
    /// </summary>
    public class PermissionServicelmpl : PermissionService
    {
        #region 注入
        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PermissionDao _permission;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        /// <param name="permission"></param>
        public PermissionServicelmpl(PermissionDao permission, LogDao logDao, LogRecord logRecord)
        {
            _permission = permission;
            _logDao = logDao;
            _logRecord = logRecord;
        }
        #endregion

        /// <summary>
        /// 根据编号获取权限功能
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Permission</returns>
        public PermissionResponse Get(int id)
        {
            var permission = _permission.Get(id);

            return new PermissionResponse() {
                Pid = permission.Pid,
                PParent = permission.PParent,
                PName = permission.PName,
                PCode = permission.PCode,
                NodeType = permission.NodeType,
                SortNo = permission.SortNo,
                Hide = permission.Hide
            };
        }

        public int Add(Permission model)
        {
            return _permission.Add(model);
        }

        public bool Delete(int id)
        {
            return _permission.Delete(id);
        }

        public List<Permission> GetList(PermissionQuery query)
        {
            return _permission.GetList(query);
        }

        public bool Update(Permission model)
        {
            return _permission.Update(model);
        }

        /// <summary>
        /// 保存或修改
        /// </summary>
        /// <returns></returns>
        public JResult<Permission> SaveOrEdit(PermissionRequest request)
        {
            var result = new JResult<Permission>()
            {
                Success = false
            };

            var permission = new Permission()
            {
                Pid = request.Pid,
                PParent = request.PParent,
                PName = request.PName,
                PCode = request.PCode,
                NodeType = request.NodeType,
                SortNo = request.SortNo,
                Hide = request.Hide,
            };

            try
            {
                if (string.IsNullOrEmpty(request.PName)) {
                    throw new Exception("权限名称不能为空！");
                }

                if (string.IsNullOrEmpty(request.PCode))
                {
                    throw new Exception("权限代码不能为空！");
                }


                if (request.Pid > 0)
                {
                    //权限名称验证
                    var queryNameResult = _permission.GetList(new PermissionQuery() { NoEqualId = request.Pid, PName = request.PName, NodeType = request.NodeType });
                    if (queryNameResult != null && queryNameResult.Any()) {
                        throw new Exception("权限名称已存在！");
                    }
                    //权限代码验证
                    var queryCodeResult = _permission.GetList(new PermissionQuery() { NoEqualId = request.Pid, PCode = request.PCode, NodeType = request.NodeType });
                    if (queryCodeResult != null && queryNameResult.Any())
                    {
                        throw new Exception("权限代码已存在！");
                    }

                    var updateStatus = _permission.Update(permission);
                    if (updateStatus)
                    {
                        //日志
                        //_logRecord.Ip = "";
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.LogType = LogRecordLogType.Permission_Update.GetHashCode();
                        _logRecord.CreateName = request.CreateName;
                        _logRecord.CreateUid = request.CreateId;
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑权限成功,权限编号：{0}", permission.Pid);
                        _logRecord.CompanyId = request.CompanyId;
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                    }
                    else {
                        throw new Exception("编辑权限失败");
                    }
                }
                else
                {
                    //权限名称验证
                    var queryNameResult = _permission.GetList(new PermissionQuery() { PName = request.PName,NodeType = request.NodeType });
                    if (queryNameResult != null && queryNameResult.Any())
                    {
                        throw new Exception("权限名称已存在！");
                    }
                    //权限代码验证
                    var queryCodeResult = _permission.GetList(new PermissionQuery() { PCode = request.PCode, NodeType = request.NodeType });
                    if (queryCodeResult != null && queryNameResult.Any())
                    {
                        throw new Exception("权限代码已存在！");
                    }

                    var permissionId = _permission.Add(permission);
                    if (permissionId > 0)
                    {
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.LogType = LogRecordLogType.Permission_Add.GetHashCode();
                        _logRecord.CreateName = request.CreateName;
                        _logRecord.CreateUid = request.CreateId;
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("新增权限成功,权限编号：{0}", permission.Pid);
                        _logRecord.CompanyId = request.CompanyId;
                        _logDao.Insert(_logRecord);
                        //日志

                        result.Success = true;
                    }
                    else {
                        throw new Exception("新增权限失败");
                    }
                }
            }
            catch (Exception ex) {
                try
                {
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.LogType = permission.Pid > 0 ? LogRecordLogType.Permission_Update.GetHashCode() : LogRecordLogType.Permission_Add.GetHashCode();
                    _logRecord.CreateName = request.CreateName;
                    _logRecord.CreateUid = request.CreateId;
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("{0}权限失败：{1}", permission.Pid > 0 ? "编辑" : "新增", ex.Message);
                    _logRecord.CompanyId = request.CompanyId;
                    _logRecord.RequestData = request.RequestData;
                    _logDao.Insert(_logRecord);
                    //日志
                    result.ErrorMessage = ex.Message;
                }
                catch {
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(UpdateStatusRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                if (_permission.UpdateStatus(request))
                {
                    //_logRecord.LogType = LogRecordLogType.Permission_Update.GetHashCode();
                    //_logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    //_logRecord.CreateDate = DateTime.Now;
                    //_logRecord.LogRemark = string.Format("更新状态成功,权限编号：{0}", request.Id);
                    //_logDao.Insert(_logRecord);

                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.LogType = LogRecordLogType.Permission_Update.GetHashCode();
                    _logRecord.CreateName = request.CreateName;
                    _logRecord.CreateUid = request.CreateId;
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新状态成功,权限编号：{0}", request.Id);
                    _logRecord.CompanyId = request.CompanyId;
                    //_logRecord.RequestData = request.RequestData;
                    _logDao.Insert(_logRecord);
                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //_logRecord.LogType = LogRecordLogType.Permission_Update.GetHashCode();
                    //_logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    //_logRecord.CreateDate = DateTime.Now;
                    //_logRecord.LogRemark = string.Format("更新状态失败,权限编号：{0}", request.Id);
                    //_logDao.Insert(_logRecord);

                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.LogType = LogRecordLogType.Permission_Update.GetHashCode();
                    _logRecord.CreateName = request.CreateName;
                    _logRecord.CreateUid = request.CreateId;
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新状态失败,权限编号：{0}", request.Id);
                    _logRecord.CompanyId = request.CompanyId;
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取功能权限列表
        /// </summary>
        /// <param name="ids">系统编号列表</param>
        /// <returns>功能权限列表</returns>
        public List<Permission> GetListByIds(List<int> ids)
        {
            return _permission.GetListByIds(ids);
        }

        /// <summary>
        /// 获取功能权限列表
        /// </summary>
        /// <param name="ids">权限编号列表</param>
        /// <returns>功能权限列表</returns>
        public List<Permission> GetListByCodes(List<string> codes)
        {
            return _permission.GetListByCodes(codes);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<PermissionResponse> GetPager(PermissionQuery query)
        {
            var pager = new PagedList<PermissionResponse>()
            {
                Success = false
            };

            var permissionPager = _permission.GetPager(query);
            if (permissionPager != null) {
                var permissionResponse = new List<PermissionResponse>();

                foreach (var item in permissionPager.TData) {
                    permissionResponse.Add(new PermissionResponse() {
                        Pid = item.Pid,
                        PParent = item.PParent,
                        PName = item.PName,
                        PCode = item.PCode,
                        NodeType = item.NodeType,
                        SortNo = item.SortNo,
                        Hide = item.Hide,
                    });
                }
                pager.TData = permissionResponse;
                pager.CurrentPageIndex = permissionPager.CurrentPageIndex;
                pager.TotalCount = permissionPager.TotalCount;
            }
            return pager;
        }
     }
}
